package com.czk.dao;

import com.czk.model.PermissionDto;
import com.czk.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/19 15:45
 */
@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDto loadByUsername(String username) {
        // sql
        String sql = "select * from t_user where username = ?";
        UserDto userDto = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(UserDto.class), username);
        return userDto;
    }

    /**
     * 拿到用户的权限
     *
     * @param userId
     * @return
     */
    public List<String> findPermissionByUserId(String userId) {
        String sql = "select * from t_permission where id in (select permission_id from t_role_permission where role_id in" +
                " (select role_id from t_user_role where user_id=?))";
        // 查询
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        List<String> stringList = new ArrayList<>(10);
        // 遍历
        list.forEach(x -> {
            stringList.add(x.getCode());
        });
        return stringList;
    }
}
